<?php

namespace App\Http\Controllers\API;

use App\ZL\Controllers\ApiBaseController;
use App\Models\Category;
use App\Repositories\CategoryRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class CategoryController
 * @package App\Http\Controllers\API
 */

class CategoryAPIController extends ApiBaseController
{
    /** @var  CategoryRepository */
    private $categoryRepository;
    private $shop_id = null;
    protected $model_name = 'App\Models\Category';
    protected $model_load_array = [
        'goods'
    ];

    public function __construct(CategoryRepository $categoryRepo)
    {
        $this->categoryRepository = $categoryRepo;
        $this->shop_id = \request('shop_id',null);
    }


    public function authLimit()
    {
        $limit = [];
        $is_all = \request('is_all');
        $limit[] =  ['shop_id', $this->shop_id];
        if(!$is_all)
            $limit[] =  ['is_in_list', '=', 1];
        return $limit;
    }

    public function index(Request $request)
    {
        $model = $this->modelPipeline([
            'modelGetAuthLimit',
            'modelGetSearch',
            'modelGetSort',
        ]);
        $model_data = clone $model;
        $count = $model->count();
        $list = $this->modelPipeline([
            'modelGetPageData',
            'collectionGetLoads',
            'modelByAfterGet',
        ],$model_data);

        return responseZK(1,$list,'',['count'=>$count]);
    }

    public function _after_get($array)
    {
        return $array;
    }

    public function _after_find(&$data)
    {
        $goods = $data->goods()->orderBy('sort')->where('status',1)->get();
        $goods->load('categories');
        $goods->load('attributesByStatus');
        $goods->load('contents');
        $goods->load('slideshow');
        $s_arr = [];
        $e_arr = [];
        foreach ($goods as $v) {
            if($v->number>0){
                $s_arr[] = $v->toArray();
            }else{
                $e_arr[] = $v->toArray();
            }
        }
        foreach ($e_arr as $v) {
            $s_arr[] = $v;
        }
        $data = $data->toArray();
        $data['goods'] = $s_arr;
    }

    /**
     * Display a listing of the Category.
     * GET|HEAD /categories
     *
     * @param Request $request
     * @return Response
     */

}
